package com.serviceprovider.business.utility;

//~--- non-JDK imports --------------------------------------------------------

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

//~--- JDK imports ------------------------------------------------------------

import java.beans.PropertyEditorSupport;

import java.text.DecimalFormat;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * User: tryk
 * Date: 24.06.11
 * Time: 15:16
 * <p/>
 * (c) All rights reserverd. Please contact tryk@lost.net.ua for any questions.
 */
public class Int2DoublePropertyEditor extends PropertyEditorSupport {
    protected final Log         logger       = LogFactory.getLog(getClass());
    private final DecimalFormat numberFormat = new DecimalFormat("######0.00");
    private final Pattern       pattern      = Pattern.compile("^\\$?(\\d+([.,]\\d{2})?)$");
    private Integer             nullValue;

    public Int2DoublePropertyEditor(boolean convertNull) {
        nullValue = convertNull
                    ? 0
                    : null;
    }

    @Override
    public void setAsText(String s) throws IllegalArgumentException {
        if (StringUtils.isEmpty(s)) {
            logger.debug("setAsText(" + s + "), setting null");
            setValue(nullValue);

            return;
        }

        Matcher m = pattern.matcher(s);

        if (m.matches()) {
            String match = StringUtils.replace(m.group(1), ",", ".");

            setValue(new Integer(Math.round(Float.valueOf(match) * 100)));
        } else {
            logger.debug("setAsText(" + s + "): illegal number, user $#,###,##0.00");

            throw new IllegalArgumentException();
        }
    }

    @Override
    public String getAsText() {
        Integer value = (Integer) getValue();

        if (value == null) {
            if (nullValue == null) {
                return null;
            } else {
                value = 0;
            }
        }

        return numberFormat.format(value / 100.0);
    }
}



